package strategies;

import exceptions.DatabaseException;
import general.IContext;
import java.util.*;

/**
 *
 * @author Alejandro
 */
public class DeleteItemsStrategy extends AbstractStrategy {

    public DeleteItemsStrategy() {
    }

    @Override
    public void executeOperation(IContext context) {
        prepareContext(context);
        if (dao != null) {
            List<Integer> deleteIds = new LinkedList<Integer>();
            Set<String> keys = pp.getParamMap().keySet();
            for (String s : keys) {
                if (s.startsWith("row_")) {
                    int newId = Integer.parseInt(s.replace("row_", ""));
                    if (pp.getParamMap().get(s).compareTo("on") == 0) {
                        deleteIds.add(newId);
                    }
                }
            }

            if (deleteIds.isEmpty()) {
                op.putErrorReport("No rows selected", "");
            }
            for (int id : deleteIds) {
                int res = 0;
                String errorMessage = "";
                try {
                    res = dao.deleteById(id);
                } catch (DatabaseException de) {
                    res = 0;
                    errorMessage = de.getMessage();
                }
                if (res == 0) {
                    op.putErrorReport("Row with id=" + id + " has external link with another rows. If you want to delete it, delete all linked rows first", errorMessage);
                } else {
                    op.putSuccessReport("Row with id=" + id + " deleted");
                }
            }
        }
    }
}
